package pers.mtx.myapplication;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import pers.mtx.myapplication.db.MyDatabaseHelper;
import pers.mtx.myapplication.model.Chatmodel.ChatRecord;
import pers.mtx.myapplication.service.WebSocketService;

public class ChatListActivity extends AppCompatActivity {
    private WebSocketService webSocketService;
    private MyDatabaseHelper dbHelper;
    private SQLiteDatabase db;
    private final OkHttpClient client = new OkHttpClient();
    private static String TAG = "ChatListActivity";
    ObjectMapper mapper = new ObjectMapper();
    @BindView(R.id.ChatList)
    LinearLayout linearLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_list_activity);
        ButterKnife.bind(this);
        Intent intentIn = getIntent();
        Intent intent = new Intent(ChatListActivity.this, WebSocketService.class);
        intent.putExtra("id", intentIn.getStringExtra("id"));
        bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
        dbHelper = new MyDatabaseHelper(ChatListActivity.this, 5);
        db = dbHelper.getReadableDatabase();
        GetChatRecord(intentIn.getStringExtra("id"));
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 1:
                    TextView data = (TextView)msg.obj;
                    data.setTextColor(Color.BLACK);
                    data.setTextSize(15);
                    linearLayout.addView(data);
                    break;
            }
        }
    };

    private void GetChatRecord(String id) {
        Request request = new Request.Builder()
                .url("http://192.168.1.109:8080/chat/init/InitHistoryChats")
                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), id))
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody responseBody = response.body()) {
                    if (!response.isSuccessful())
                        throw new IOException("Unexpected code " + response);
                    String string = responseBody.string();
                    if (!string.equals("")){
                        List<ChatRecord> chatRecords = mapper.readValue(string, new TypeReference<List<ChatRecord>>(){});
                        chatRecords.stream().forEach(e ->{
                            ContentValues values = new ContentValues();
                            values.put("send_time",e.getSendtime().toString());
                            values.put("sender_id",e.getSenderid());
                            values.put("receiver_id",e.getReceiverid());
                            values.put("message",e.getMessage());
                            values.put("msg_type",e.getMsgtype());
                            values.put("rb",e.getRollback());
                            values.put("msg_id",e.getMsgid());
                            db.insertOrThrow("chat_record",null,values);
                        });
                    }

                    SetupDataByDb();

                }
            }
        });
    }

    private void SetupDataByDb() {
        Cursor cursor = db.query("User", null, null, null, null, null, null);
        //如果索引在第一条就开始执行
        if (cursor.moveToFirst()) {
            do {
                //通过列名找到数据
                @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex("nickName"));
                @SuppressLint("Range") String id = cursor.getString(cursor.getColumnIndex("userName"));
                Log.i("data", "id为" + id + "名字为" + name);
                // 聊天名
                TextView textView = new TextView(ChatListActivity.this);
                textView.setText(name);
                textView.setTag(id);
                ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 200);
                textView.setLayoutParams(layoutParams);
                textView.setOnClickListener(v -> {
                    Intent intent = new Intent(ChatListActivity.this, ChatActivity.class);
                    intent.putExtra("conversinerId",id);
                    intent.putExtra("name",name);
                    startActivity(intent);
                });
                Message message = new Message();
                message.what=1;
                message.obj = textView;
                handler.sendMessage(message);
            } while (cursor.moveToNext());

        }
        //使用完需要关闭
        cursor.close();
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) iBinder;
            webSocketService = binder.getService();
            Log.d("ChatActivity", "onServiceConnected");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("ChatActivity", "onServiceDisconnected");
        }
    };




}
